﻿using System;
using System.Collections.Generic;
using MyHealthByDesign.Domain;
using System.Web.UI.WebControls;


namespace MyHealthByDesign.Admin
{
    
    /// <summary>
    /// Description:
    /// Displays website option maintenance for a provided question
    /// 
    /// Author: Mark Servais
    /// Date Created: 12/10/2011
    /// 
    /// Other code files referenced:
    /// None.
    /// 
    /// Regression Test Information:
    /// None.
    /// 
    /// Revision History:
    /// None. 
    /// 
    /// Known Faults:
    /// None.
    /// </summary>
    public partial class MaintainOptions : System.Web.UI.Page
    {
        Domain.Domain domain = new Domain.Domain();

        /// <summary>
        /// Page Load event handler - check if admin is logged in
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Page displayed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!domain.IsAdminLoggedIn())
            {
                Response.Redirect("Default.aspx");
            }

            if (!Page.IsPostBack)
            {
                // load list box
                LoadOptionList();

                // set button visibility
                ResetButtons();

                int nQuestionId = (int)Session["OptionQuestionID"];
                Question q = domain.RetrieveQuestion(nQuestionId);

                lblQuestionLabel.Text = q.ContentLabel;
            }

            
        }

        /// <summary>
        /// LoadOptionList - populates options in list box fo maintenance
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Page displayed
        /// </summary>
        private void LoadOptionList()
        {
            lbOptions.Items.Clear();

            // add first item
            lbOptions.Items.Add(new ListItem("<Add new Option>", "AA"));

            int nQuestionID = (int) Session["OptionQuestionID"];
            
            List<QuestionOption> lstQuestionOptions = domain.RetrieveQuestionOptions(nQuestionID);

            //hold in Session for late use
            Session["OptionList"] = lstQuestionOptions;

            // add database items)
            foreach (var questionOption in lstQuestionOptions)
            {
                lbOptions.Items.Add(new ListItem(questionOption.OptionLabel, questionOption.Id.ToString()));
            }

            foreach (ListItem item in lbOptions.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }

        /// <summary>
        /// ResetButtons - resets maintenance buttons
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Page displayed
        /// </summary>
        protected void ResetButtons()
        {

            lblErrors.Visible = false;
            btnMoveUp.Visible = false;
            btnMoveDown.Visible = false;
            btnDelete.Visible = false;
            pnlSubmit.Visible = false;
            pnlOptionCore.Visible = false;
        }

        /// <summary>
        /// lbOptions_SelectedIndexChanged - question selection made
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Appropriate options are loaded and displayed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbOptions_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (lbOptions.SelectedIndex == 0)
            {
                btnMoveUp.Visible = false;
                btnMoveDown.Visible = false;

                // other addition tasks
                tbOptionFieldName.Text = string.Empty;
                tbOptionLabel.Text = string.Empty;
                tbOptionCSS.Text = string.Empty;
                tbOptionHelpURL.Text = string.Empty;
                cbSpecial.Checked = false;
                tbOptionSpecial.Text = string.Empty;

                btnDelete.Visible = false;
                pnlOptionCore.Visible = true;
                pnlSubmit.Visible = true;
            }
            else
            {
                if (lbOptions.SelectedIndex == 1)
                    btnMoveUp.Visible = false;
                else
                    btnMoveUp.Visible = true;

                if (lbOptions.SelectedIndex == (lbOptions.Items.Count - 1))
                    btnMoveDown.Visible = false;
                else
                    btnMoveDown.Visible = true;

                btnDelete.Visible = true;
                pnlSubmit.Visible = true;
                

                // update form
                List<QuestionOption> lstOptions = (List<QuestionOption>)Session["OptionList"];
                QuestionOption selectedOption = new QuestionOption();

                foreach (var questionOption in lstOptions)
                {
                    if (questionOption.Id == Convert.ToInt32(lbOptions.SelectedValue))
                    {
                        selectedOption = questionOption;
                    }
                }

                tbOptionFieldName.Text = selectedOption.Name;
                tbOptionLabel.Text = selectedOption.OptionLabel;
                tbOptionCSS.Text = selectedOption.OptionCSS;
                tbOptionHelpURL.Text = selectedOption.OptionHelpURL;

                if (selectedOption.Specials.Count > 0)
                {
                    cbSpecial.Checked = true;
                    tbOptionSpecial.Text = selectedOption.Specials[0].Name;
                }
                else
                {
                    cbSpecial.Checked = false;
                    tbOptionSpecial.Text = string.Empty;
                }

                pnlOptionCore.Visible = true;

            }


        }

        /// <summary>
        /// btnMoveUp_Click - update question sort
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Appropriate questions are loaded and displayed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMoveUp_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            // get selected question
            QuestionOption selectedOption = new QuestionOption();
            List<QuestionOption> lstOptions = (List<QuestionOption>)Session["OptionList"];

            foreach (var questionOption in lstOptions)
            {
                if (questionOption.Id == Convert.ToInt32(lbOptions.SelectedValue))
                {
                    selectedOption = questionOption;
                }
            }

            // get previous question in the list
            QuestionOption swapOption = new QuestionOption();
            
            foreach (var questionOption in lstOptions)
            {
                if (questionOption.Id == Convert.ToInt32(lbOptions.Items[lbOptions.SelectedIndex - 1].Value))
                {
                    swapOption = questionOption;
                }
            }
            
            // swap sort order
            int selectedOrder = selectedOption.SortOrder;
            selectedOption.SortOrder = swapOption.SortOrder;
            swapOption.SortOrder = selectedOrder;

            // update each option
            domain.UpdateOption(swapOption);
            domain.UpdateOption(selectedOption);
            
            // rebuild list box
            LoadOptionList();
            ResetButtons();
        }

        /// <summary>
        /// btnMoveDown_Click - update question sort
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Appropriate questions are loaded and displayed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMoveDown_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            // get selected question
            QuestionOption selectedOption = new QuestionOption();
            List<QuestionOption> lstOptions = (List<QuestionOption>)Session["OptionList"];

            foreach (var questionOption in lstOptions)
            {
                if (questionOption.Id == Convert.ToInt32(lbOptions.SelectedValue))
                {
                    selectedOption = questionOption;
                    break;
                }
            }

            // get next question in the list
            QuestionOption swapOption = new QuestionOption();

            foreach (var questionOption in lstOptions)
            {
                if (questionOption.Id == Convert.ToInt32(lbOptions.Items[lbOptions.SelectedIndex + 1].Value))
                {
                    swapOption = questionOption;
                    break;
                }
            }

            // swap sort order
            int selectedOrder = selectedOption.SortOrder;
            selectedOption.SortOrder = swapOption.SortOrder;
            swapOption.SortOrder = selectedOrder;

            // update each option
            domain.UpdateOption(swapOption);
            domain.UpdateOption(selectedOption);

            // rebuild list box
            LoadOptionList();
            ResetButtons();
        }

        /// <summary>
        /// btnDelete_Click - delete question
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Appropriate questions are flagged as deactivated
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            // get selected question
            QuestionOption selectedOption = new QuestionOption();
            List<QuestionOption> lstOptions = (List<QuestionOption>)Session["OptionList"];

            foreach (var questionOption in lstOptions)
            {
                if (questionOption.Id == Convert.ToInt32(lbOptions.SelectedValue))
                {
                    selectedOption = questionOption;
                    break;
                }
            }

            selectedOption.SortOrder = 0;

            // update option
            domain.UpdateOption(selectedOption);
            domain.UpdateOptionStatusByValue(Convert.ToInt32(lbOptions.SelectedValue), false);

            // rebuild list box
            LoadOptionList();
            ResetButtons();
        }

        /// <summary>
        /// btnSubmit_Click - submit Option form
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Form submitted for processing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            QuestionOption questionOption = new QuestionOption();
            List<QuestionOption> qOptions = (List<QuestionOption>)Session["OptionList"];
            int lastSort = 0;

            if (lbOptions.SelectedValue == "AA")
            {
                questionOption = new QuestionOption();
                questionOption.Id = 0;
                foreach (QuestionOption qo in qOptions)
                {
                    lastSort = qo.SortOrder;
                }

                questionOption.SortOrder = lastSort + 1;
            }
            else
            {
                foreach(QuestionOption qo in qOptions)
                {
                    if(qo.Id == Convert.ToInt32(lbOptions.SelectedValue))
                    {
                        questionOption = qo;
                        break;
                    }
                }
            }

            // populate questionOption from screen
            questionOption.Name = tbOptionFieldName.Text;
            questionOption.OptionLabel = tbOptionLabel.Text;
            questionOption.OptionCSS = tbOptionCSS.Text;
            questionOption.OptionHelpURL = tbOptionHelpURL.Text;

            if (cbSpecial.Checked)
            {
                OptionSpecial os = new OptionSpecial();
                if(questionOption.Specials.Count > 0)
                {
                    os = questionOption.Specials[0];
                    os.Name = tbOptionSpecial.Text;
                }
                else
                {
                    questionOption.Specials = new List<OptionSpecial>();
                    os.Name = tbOptionSpecial.Text;
                    os.DisplayType = "System.Web.UI.WebControls.TextBox";
                    questionOption.Specials.Add(os);
                }
                
            }
            else
            {
                if (questionOption.Specials != null)
                    questionOption.Specials.Clear();
                else
                    questionOption.Specials = new List<OptionSpecial>();
            }

            // add or update
            if (questionOption.Id == 0)
                domain.InsertQuestionOptionCore(questionOption, (int)Session["OptionQuestionID"]);
            else
                domain.UpdateOption(questionOption);

            LoadOptionList();
            ResetButtons();
        }

        /// <summary>
        /// btnReturnToQuestion_Click - redirect back to question
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Returned to maintain questions
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnReturnToQuestion_Click(object sender, EventArgs e)
        {
            int nq = (int) Session["OptionQuestionID"];
            int nc = (int) Session["OptionQuestionCategoryID"];

            Response.Redirect("MaintainQuestions.aspx?q=" + nq + "&c=" + nc);
        }
    }
}